# -*- coding: utf-8 -*-
# Project  : rabbitmq_demo
# FileName : product.py
# Time     : 2021/1/14 14:29
# Author  : Mason101

# 生产者，关键字模式

import pika
import json


class DirectProduct:
    def __init__(self):
        self.host = "127.0.0.1"
        self.port = 5672
        self.username = "guest"
        self.password = "guest"
        self.connection = self.create_connection()
        self.channel = self.create_channel()

    # 创建连接
    def create_connection(self):
        credentials = pika.PlainCredentials(username=self.username, password=self.password, erase_on_connect=True)
        connection = pika.BlockingConnection(pika.ConnectionParameters(self.host, self.port, "/", credentials))
        print(connection)
        return connection

    # 声明管道
    def create_channel(self):
        channel = self.connection.channel()
        channel.exchange_declare(exchange="python-test", durable=True)      # 交换机、持久化
        return channel

    # 发送数据
    def send_data(self):
        for i in range(10):
            msg = json.dumps({"id": i + 1, "user": self.username})
            print(msg)
            self.channel.basic_publish(exchange="python-test", routing_key="id", body=msg,
                                       properties=pika.BasicProperties(delivery_mode=2))    # 1-消息非持久化，2-持久化

    # 关闭管道
    def close(self):
        self.connection.close()


if __name__ == '__main__':
    product_obj = DirectProduct()
    product_obj.send_data()
    product_obj.close()
